<template>
  <div class="artList">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="reflashText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <articleItem
          :article="item"
          v-for="(item, index) in list"
          :key="index"
        ></articleItem>
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArtList } from '@/api/article'
import articleItem from '@/components/artItem'
export default {
  props: ['artlist'],
  components: {
    articleItem
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isLoading: false,
      reflashText: '刷新成功'
    }
  },

  created () {},

  methods: {
    //   List 组件通过 loading 和 finished 两个变量控制加载状态，当组件滚动到底部时，会触发 load 事件并将 loading 设置成 true。此时可以发起异步操作并更新数据，数据更新完毕后，将 loading 设置成 false 即可。若数据已全部加载完毕，则直接将 finished 设置成 true 即可。
    async onLoad () {
      try {
        const res = await getArtList({
          channel_id: this.artlist.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        this.list.push(...res.data.data.results)
        this.loading = false
        if (res.data.data.pre_timestamp) {
          this.timestamp = res.data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const res = await getArtList({
          channel_id: this.artlist.id,
          timestamp: Date.now(),
          with_top: 1
        })

        if (Math.random() > 0.5) {
          return JSON.parse('123qe')
        }

        this.list.unshift(...res.data.data.results)
        this.isLoading = false
        this.reflashText = '刷新成功'
      } catch (error) {
        this.reflashText = '刷新失败'
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.artList {
  height: 84vh;
  overflow-y: auto;
}
</style>
